package com.woyou.component;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.jing.biandang.R;
import com.woyou.Constants;
import com.woyou.activity.HomeActivity;
import com.woyou.bean.Order;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.HandleOrderReq;
import com.woyou.bean.rpc.Result;
import com.woyou.bean.rpc.SetShopStatusReq;
import com.woyou.event.EventModifyShopStatus;
import com.woyou.model.OrderManageModel;
import com.woyou.model.rpc.OrderModel;
import com.woyou.model.rpc.ShopModel;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.ThreadPoolManager;

import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import de.greenrobot.event.EventBus;
import retrofit.RetrofitError;

public class NewOrderCancelPop implements OnClickListener {
	private HomeActivity homeActivity;
	private RelativeLayout positionView;
	private PopupWindow popupWindow;
	private RelativeLayout pop_neworder_reorder_nobody;
	private RelativeLayout pop_neworder_reorder_busy;
	private RelativeLayout pop_neworder_reorder_outofrange;
	private RelativeLayout pop_neworder_reorder_rest;
	
	// 定时器定时改变营业状态
	private Timer timer;
	private TimerTask timerTask;

	private OrderModel orderModel;
	private OrderManageModel omModel = OrderManageModel.getInstance();
	private SetShopStatusReq setShopStatusReq = new SetShopStatusReq();				//设置店铺营业状态
	private int currentOrder=0;
	
	public NewOrderCancelPop(HomeActivity homeActivity, RelativeLayout positionView) {
		this.homeActivity = homeActivity;
		this.positionView = positionView;
		orderModel = OrderModel.getInstance(homeActivity);
		UserInfo userInfo = LoginUtils.getUserInfo(homeActivity);
		if ( userInfo!=null ){
			setShopStatusReq.setsId(userInfo.getsId());
			setShopStatusReq.setPwd(userInfo.getPwd());
		}
	}

	/**
	 * 弹出泡泡窗体
	 */
	public void showPopup(int currentOrder) {
		//当前新订单在列表中的位置
		this.currentOrder=currentOrder;
		// 实例化泡泡窗台的布局文件
		View contentView = LayoutInflater.from(homeActivity).inflate(
				R.layout.pop_neworder_reorder, null);
		pop_neworder_reorder_nobody = (RelativeLayout) contentView
				.findViewById(R.id.pop_neworder_reorder_nobody);
		pop_neworder_reorder_busy = (RelativeLayout) contentView
				.findViewById(R.id.pop_neworder_reorder_busy);
		pop_neworder_reorder_outofrange = (RelativeLayout) contentView
				.findViewById(R.id.pop_neworder_reorder_outofrange);
		pop_neworder_reorder_rest = (RelativeLayout) contentView
				.findViewById(R.id.pop_neworder_reorder_rest);

		pop_neworder_reorder_nobody.setOnClickListener(this);
		pop_neworder_reorder_busy.setOnClickListener(this);
		pop_neworder_reorder_outofrange.setOnClickListener(this);
		pop_neworder_reorder_rest.setOnClickListener(this);

		// 实例化泡泡窗体
		if (popupWindow == null) {
			popupWindow = new PopupWindow(contentView, 270,ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 显示泡泡窗体
		// popupWindow.showAtLocation(positionView, Gravity.LEFT |
		// Gravity.BOTTOM, 0, 110);
		popupWindow.showAsDropDown(positionView, 0, 30);
	}

	/**
	 * 隐藏pop窗体
	 */
	public void hidePopup() {
		if (popupWindow != null && popupWindow.isShowing()) {
			popupWindow.dismiss();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.pop_neworder_reorder_nobody:
			// 统计拒绝订单的次数
			Constants.refuseOrderNum++;
			RefuseNewOrder(1);
			break;
		case R.id.pop_neworder_reorder_busy:
			// 统计拒绝订单的次数
			Constants.refuseOrderNum++;
			RefuseNewOrder(3);
			break;
		case R.id.pop_neworder_reorder_outofrange:
			// 统计拒绝订单的次数
			Constants.refuseOrderNum++;
			RefuseNewOrder(4);
			break;
		case R.id.pop_neworder_reorder_rest:
			// 重置订单次数
			Constants.refuseOrderNum = 0;
			RefuseNewOrder(2);
			closeShop();
			break;
		}
		popupWindow.dismiss();
		if (Constants.refuseOrderNum >= 2&&!Constants.shopStatus.equals("C")) {
			settingShopBusy();
		}
	}

	/**
	 * 设置店铺状态繁忙
	 */
	public void settingShopBusy() {
		// 取消连接中
		homeActivity.actionbarView.isSettingShopStatus = false;
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					setShopStatusReq.setStatus("B");
					Result result = ShopModel.getInstance(homeActivity).setShopStatus(setShopStatusReq);
					if ( result!=null && result.code==1 ) {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// 设置营业状态
								Constants.shopStatus = "B";
								// 标记繁忙状态1小时
								homeActivity.actionbarView.busyStatus = 1;
								homeActivity.actionbarView.layout_actionbar_choice.setBackgroundResource(R.raw.actionbar_state_yellow);
								homeActivity.actionbarView.layout_actionbar_choice_tv.setText("繁忙1小时");
								homeActivity.menuView.menuStatus.setImageResource(R.raw.icon_menu_status_busy);
								EventBus.getDefault().post(new EventModifyShopStatus("B"));
								homeActivity.menuView.isRefreshAtTime=false;
								busy2Business(1);
							}
						});
					} else if( result != null && result.code==-3){
						homeActivity.homeController.exitLogin();
					} else {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "设置失败");
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 繁忙定时转到正常营业
	 * 
	 * @param type
	 *            1:繁忙一小时 2:繁忙两小时
	 */
	public void busy2Business(int type) {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
		}
		timer = new Timer();
		timerTask = new TimerTask() {
			@Override
			public void run() {
				//重置繁忙中
				homeActivity.actionbarView.busyStatus=0;
				// 重置订单次数
				Constants.refuseOrderNum = 0;
				homeActivity.menuView.init();
			}
		};
		switch (type) {
		case 1:
			timer.schedule(timerTask, 1 * 60 * 60 * 1000);
			break;
		case 2:
			timer.schedule(timerTask, 2 * 60 * 60 * 1000);
			break;
		}
	}

	/**
	 * 关闭店铺
	 */
	public void closeShop() {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					setShopStatusReq.setStatus("C");
					Result result = ShopModel.getInstance(homeActivity).setShopStatus(setShopStatusReq);
					if ( result!=null && result.code==1 ) {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// 设置营业状态
								Constants.shopStatus = "C";
								homeActivity.actionbarView.layout_actionbar_choice.setBackgroundResource(R.raw.actionbar_state_red);
								homeActivity.actionbarView.layout_actionbar_choice_tv.setText("休息");
								homeActivity.menuView.menuStatus.setImageResource(R.raw.icon_menu_status_rest);
								EventModifyShopStatus eventModifyShopStatus = new EventModifyShopStatus("C");
								EventBus.getDefault().post(eventModifyShopStatus);
							}
						});
					} else if( result != null && result.code==-3  ){
						homeActivity.homeController.exitLogin();
					} else {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "设置失败");
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 拒绝订单选择理由
	 */
	public void RefuseNewOrder(final int location) {

		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				List<String> newOrderList = homeActivity.homeController.newOrderList;
				// 如果拒绝理由为空
				HandleOrderReq handleOrderReq = new HandleOrderReq();
				handleOrderReq.setoId(newOrderList.get(currentOrder));
				handleOrderReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
				handleOrderReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
				handleOrderReq.setHandle(2);
				handleOrderReq.setRefuse(location);
				try {
					final Result<Order> result = orderModel.handleOrder(handleOrderReq);
					if ( newOrderList!=null && newOrderList.size()>0  ) {
						if ( newOrderList.size()>currentOrder){
							newOrderList.remove(currentOrder);
						} else {
							newOrderList.remove(0);
						}
					}
					if (result != null && result.getCode() == 1) {
						// 移除新订单列表的第一个数据并将新的newOrderList存储到aCache中
						omModel.addNewOrder2Invalid(result.getData());
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, result.getMsg());
							}
						});
					}
				} catch (RetrofitError error) {
					switch (error.getKind()) {
					case NETWORK:
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "网络异常，请检查您的网络!");
							}
						});
						break;
					}
				}
				// 判断订单列表newOrderList.size()是否为小于0，如果小于0返回订单页面，如果大于0继续接单
				int hasData = newOrderList.size();
				if (hasData <= 0) {
					homeActivity.getNewOrderFm().hasNextOrder();
				} else {
					homeActivity.getNewOrderFm().initData();
				}
			}
		});
	}
}
